const {comMysql} = require("../db/mysql")
const xss = require("xss")

const addComment = (req,res)=>{
  let {username,content,blogId,realname,avatar} = req.body  
  content = xss(content)
  let time = new Date().getTime()
  let sql = `insert into comment(username,content,time,goodNum,blogId,realname,avatar) values (?,?,?,?,?,?,?)`
  let arr = [username,content,time,0,blogId,realname,avatar]
  
  return comMysql(sql,arr)
}

const delComment = (req,res)=>{
  let {id,username} = req.body
  let sql = `delete from comment where id =? and username = ?`
  let arr = [id,username]
  return comMysql(sql,arr)
}
const updateComment = (req,res)=>{
  let {id,goodNum} = req.body
  let sql = `update comment set goodNum = ? where id = ?`
  let arr = [goodNum,id]
  console.log(sql);
  console.log(arr);
  
  
  return comMysql(sql,arr)
  
}

const searchComment = (req,res)=>{
  let {username,goodNum,time,blogId} = req.query
  let sql = `select comment.username,comment.content,comment.goodNum,comment.id,
  comment.time,users.avatar,users.realname
  from comment LEFT JOIN users on comment.username=users.username where 1=1 `
  if(username){
    sql+=`and username = ${username} `
  }
  if(blogId){
    sql+=`and blogId = ${blogId} `
  }
  if(goodNum){
    sql+=`order by goodNum desc`
  }
  if(time){
    sql+=`order by time desc`
  }
  
  return comMysql(sql)

}

module.exports={
  addComment,
  delComment,
  searchComment,
  updateComment
}